$(function () {
    let productId = localStorage.getItem("productId");
    findById(productId);
})

function findById(id) {
    let data = myAjax("/back/product/findById", {id: id}, "get");
    findAll(data);
}

function findAll(data) {
    let productModel = data.productModel;
    let html = '';
    data = data.list;
    for (let i = 0; i < data.length; i++) {
        html += ' <option value="' + data[i].id + '">' + data[i].name + '</option>';
    }
    $("#cuisine").html(html);
    setProductData(productModel);
}

function setProductData(data) {
    $("#cuisine option[value=" + data.cuisineId + "]").prop("selected", true);
    $("#name").val(data.name);
    $("#showImg").attr("src", data.imgHref);
    $("#normalPrice").val(data.normalPrice);
    $("#price").val(data.price);
    $("#content").val(data.content);
    $("input[name='isShow'][value=" + data.isShow + "]").attr("checked", true);
    $("input[name='isRecommend'][value=" + data.isRecommend + "]").attr("checked", true);
}

function save() {
    let formData = new FormData();
    formData.append("id", localStorage.getItem("productId"));
    formData.append("cuisine", $("#cuisine").val());
    formData.append("name", $("#name").val());
    formData.append('imgHref', $('#imgHref')[0].files[0]);
    formData.append("normalPrice", $("#normalPrice").val());
    formData.append("price", $("#price").val());
    formData.append("content", $("#content").val());
    formData.append("isShow", $("input[name=isShow]:checked").val());
    formData.append("isRecommend", $("input[name=isRecommend]:checked").val());

    $.ajax({
        url: '/back/product/update',
        type: 'POST',
        dataType: "json",
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {
            if (data.result == 1) {
                $('#right').load('/html/back/product/productManage.html');
            } else {
                alert("修改失敗");
            }
        }
    });
}